package com.kx.config.shiro.reamls;

import com.kx.bean.User;
import com.kx.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("==================执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:*");

        //拿到当前登录的对象
//        Subject subject= SecurityUtils.getSubject();
//        User currentUser = (User) subject.getPrincipal();   //拿到User对象
//
//        info.addStringPermission(currentUser.getPerms());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("==================执行了认证");
        //用户名 密码——数据中取
//        String name = "root";
//        String password = "123";
//        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
//        if (!usernamePasswordToken.getUsername().equals(name)){
//            return null;    //抛出异常  UnknownAccountException
//        }
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        User user = userService.queryUserByName(usernamePasswordToken.getUsername());
        if (user == null) {
            return null;
        }
        Subject currentSubject=SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);
        //密码认证  shiro完成
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
